<template>
  <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
    <el-form-item label="唯一标识" prop="relkey" required>
      <el-input v-model="formItem.relkey" placeholder="请输入唯一标识" />
    </el-form-item>
    <el-form-item label="名称" prop="name" required>
      <el-input v-model="formItem.name" placeholder="请输入名称" />
    </el-form-item>
    <el-form-item label="源模型描述" prop="srcdesc" required>
      <el-input v-model="formItem.srcdesc" placeholder="请输入源模型描述" />
    </el-form-item>
    <el-form-item label="目标模型描述" prop="destdesc" required>
      <el-input v-model="formItem.destdesc" placeholder="请输入目标模型描述" />
    </el-form-item>
  </el-form>
</template>

<script>
import { create, update, detail } from '@neu/cmdb-ui/api/relationtype'

// 定义一个表单原始项
const formItem = {
  name: '',
  relkey: '',
  srcdesc: '',
  destdesc: '',
  dir: '',
  buildin: false
}
export default {
  name: 'RelationTypeEditForm',
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formItem: { ...formItem },
      // 表单验证规则
      rules: {
        relkey: [
          { required: true, message: '唯一标识不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        srcdesc: [
          { required: true, message: '源模型描述不能为空', trigger: 'blur' }
        ],
        destdesc: [
          { required: true, message: '目标模型描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    edited() {
      return this.id !== ''
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function(newVal, oldVal) {
      if (newVal !== '') {
        this.fetch()
      }
    }
  },
  created() {
    // 表单组件放在diaolog中，首次打开时，监控不到id的变化。所以需要在created中调用一次
    if (this.id !== '') {
      this.fetch()
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== '') {
        detail(this.id).then(response => {
          const { _id, ...data } = response.data
          this.formItem = data
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.edited
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
